(function(){
    var that;
    function Game () {
        this.food = new Food ()
        this.snake = new Snake ()
        this.map = map
        that = this
    }
    Game.prototype.start = function (map) {
        this.food.render(this.map)
        this.food.render(this.map)
        this.snake.render(this.map)
        RunSnake();
        change();
    } 
    function change() {
        document.onkeydown = function (e) {
            switch(e.keyCode) {
                case 37:
                    that.snake.direction = "left";
                    break;
                case 38:
                    that.snake.direction = "top";
                    break;
                case 39:
                    that.snake.direction = "right";
                    break;
                case 40:
                    that.snake.direction = "bottom";
                    break;
            }
        }
    };
    function RunSnake() {
        var timer = setInterval(function ti(){
            // 蛇开始运动
            that.snake.move();
            that.snake.remove(this.map)
            that.snake.render(this.map)
            // 判断是否吃到食物
            var foodX = that.food.x
            var foodY = that.food.y
            var maxX = that.map.offsetWidth/that.snake.width
            var maxY = that.map.offsetHeight/that.snake.height 
            var headx = that.snake.body[0].x
            var heady = that.snake.body[0].y
            var hx = headx*that.snake.width
            var hy = heady*that.snake.height
            // if (foodX ===hx&&foodY===hy) {
            //     that.food.remove(that.map,0)
            //     that.food.render(that.map)
            //     var last = that.snake.body[that.snake.body.length-1]
            //     that.snake.body.push({x:last.x,y:last.y,color:last.color})
            // }
            for (i = 0; i <that.food.element.length;i++) {
                if (that.food.element[i].offsetLeft === hx && that.food.element[i].offsetTop ===hy) {
                    that.food.remove(that.map,i)
                    that.food.render(that.map)
                    var last = that.snake.body[that.snake.body.length-1]
                    that.snake.body.push({x:last.x,y:last.y,color:last.color})
                }
            }
            // 当蛇头位置超过map的宽度，游戏结束
            if (headx >= maxX || heady >=maxY ||heady<0||headx<0) {
                clearInterval(timer)
                alert("游戏结束")
            }
            // 当蛇头接触到蛇身，游戏结束
            for (i = that.snake.body.length-1;i>0;i--) {
                if (that.snake.body[i].x ===headx&&that.snake.body[i].y ===heady) {
                    clearInterval(timer)
                    alert("游戏结束")
                }
            }
        },160)
    }
    window.Game =Game;
})();